package com.changgou.jwt;

import io.jsonwebtoken.*;

import org.bouncycastle.util.encoders.Base64Encoder;
import org.junit.Test;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName CreteCoken
 * @Description 创建与解析token
 * @Author 洛尘
 * @Date 15:28 2019/11/20
 * @Version 2.1
 **/
public class CreteCoken {


    /**
     * 生成token
     */
    @Test
    public void test01(){

        JwtBuilder builder = Jwts.builder();

        //1、创建头部
        Map<String,Object> header = new HashMap<>();
        header.put("alg","HS256");
        header.put("typ","JWT");
        builder.setHeader(header);

        //2、创建载荷
//        builder.setId("1");
        builder.setIssuer("狗娃");
//        builder.setIssuedAt(new Date());
        //设置过期时间
        //builder.setExpiration(new Date(System.currentTimeMillis() + 30000));
        //3、添加签名   10110101
        builder.signWith(SignatureAlgorithm.HS256, "aaaa");
//        builder.signWith(SignatureAlgorithm.HS256,"itheima");

        //4、生成(令牌)token
        String token = builder.compact();
        System.out.println(token);
    }

    @Test
    public void coken(){
        //1、解析令牌
        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiLni5flqIMiLCJleHAiOjE1NzQyNTM5OTZ9.uOJ6NLFuVyxnVayLXisH7VrqAuEVQ3tASNBiU5IaR4Q";
        JwtParser parser = Jwts.parser();
        parser.setSigningKey("aaaa");
        Jws<Claims> claimsJws = parser.parseClaimsJws(token);
        System.out.println("claimsJws = " + claimsJws);
    }

    @Test
    public void teset00(){
        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxIiwiaXNzIjoi54uX5aiDIiwiaWF0IjoxNTc0MjM5NTM1LCJleHAiOjE1NzQyMzk1NjV9.6O5H8zTIuVOKD2ColPmQqvs9YgsXTL9kAmxxAh38FAU";
        // 创建解析对象
        JwtParser parser = Jwts.parser();
        parser.setSigningKey("itheima");
        Claims claims = parser.parseClaimsJws(token).getBody();
        Jws<Claims> claimsJws = parser.parseClaimsJws(token);
        System.out.println("claimsJws = " + claimsJws);
        System.out.println(claims);
    }

}
